//index.js
import mallApi from '../../service/mallApi'
import activityApi from '../../service/activityApi'
import goodsApi from '../../service/goodsApi'
import { parseQuery } from '../../utils/util'
//获取应用实例
const app = getApp()
Page({
    data: {
        searchKeyRecommend: '搜索',
        hasUserInfo: false,
        currentPage: 'index',
        optionTalentId: '',
        menuArea: [{
            type: 0,
            name: '每日抽奖',
            picUrl: `${app.globalData.picBaseUrl}/index/20190426/luck-draw-everyday.png`
        }, {
            type: 1,
            name: '运动服饰',
            picUrl: `${app.globalData.picBaseUrl}/index/20190426/sportswear.png`
        }, {
            type: 2,
            name: '潮流好鞋',
            picUrl: `${app.globalData.picBaseUrl}/index/20190426/fashion-shoes.png`
        }, {
            type: 99,
            name: '新品速递',
            picUrl: `${app.globalData.picBaseUrl}/index/20190426/new-products.png`
        }], // 金刚区
        activityList: [], // 拔草专区
        bannerList: [],
        talentInfo: {
            headUrl: '',
            nickName: '',
            isTalent: false
        },
        recommendGoodsList: [],
        goodsList: [],
        startPage: '1',
        pageSize: '50',
        userInfo: {},
        showSharePopup: false,
        talentId: '',
        loadTips: '加载中...',
        itemTapFlag: false, // 商品点击 flag
        showCommissionRules: false, // 返佣规则显示 flag ，店主首次分享显示，缓存判断
        firstShared: false, // 是否分享过一次了， false 首次分享，true 非首次分享
        showChooseSharePop: false, // 是否显示分享的选择浮窗
        nextFlag: false, // 是否有下一页
        loadNextPageFlag: true, // 是否正在加载下一页
        cardPopup: false, // 获奖弹窗
        picBaseUrl: app.globalData.picBaseUrl, // 网络图片基本路径
        giftId: '', // 收到礼物ID
        giftAmount: null, // 收到礼物数量
    },
    onLoad: function(options) {
        let that = this
        console.log(this.route, 'route')
        console.log(options, 'options')
        let sceneObj = {}
        if (options.scene) {
            sceneObj = parseQuery(options.scene)
            console.log(sceneObj)
        }
        if (options.targetPage) {
            if (options.targetPage === 'vote') {
                wx.navigateTo({
                    url: '/pages/vote/vote?userId=' + options.userId
                })
            } else if (options.targetPage === 'teamDetail') {
                wx.navigateTo({
                    url: `/pages/teamDetail/teamDetail?userId=${options.userId}&teamNo=${options.teamNo}`
                })
            }
        }
        // 收到礼物
        if (options.giftId) {
            this.setData({
                giftId: options.giftId,
                popupType: 'GIFTS_FROM_FRIENDS'
            })
        } else {
            this.setData({
                popupType: 'CONGRATULATIONS_GET_REWARD'
            })
        }

        let storageTalentId = wx.getStorageSync('talentId')
        that.setData({
                onLoadFlag: true
            })
            // 开通达人店提示
        if (options.openTalent) {
            wx.showToast({
                title: '恭喜成为小布达人，快去分享好货吧!',
                icon: 'none'
            })
        }
        if (options.talentId) {
            that.setData({
                optionTalentId: options.talentId
            })
        } else if (options.scene && sceneObj.talentId) {
            that.setData({
                optionTalentId: sceneObj.talentId
            })
        }
        if (app.globalData.userToken) {
            // app.js 里获取了用户信息
            that.setData({
                userInfo: app.globalData.userInfo,
                hasUserInfo: true
            })
            let talentId = wx.getStorageSync('talentId')
            if (talentId && (that.data.optionTalentId == '')) {
                console.log('COVER - 2')
                that.setData({
                    optionTalentId: talentId
                })
            }
            that.initData()
        } else {
            // 判断是否有授权，有授权的话从回调调用方法初始化数据
            // 无授权的话直接调用方法初始化数据
            wx.getSetting({
                success: res => {
                    if (res.authSetting['scope.userInfo']) {
                        if (app.globalData.userToken) { // 如果缓存中读取到 userToken 设置
                            let talentId = wx.getStorageSync('talentId')
                            if (talentId && (that.data.optionTalentId == '')) { // 如果缓存中存在达人店 id 进行设置
                                console.log('COVER - 3')
                                that.setData({
                                    optionTalentId: talentId
                                })
                            }
                            that.initData()
                        } else {
                            app.checkStatusCallback = res => {
                                that.setData({
                                    userInfo: res.userToken,
                                    hasUserInfo: true
                                })
                                if (res.talentId && (that.data.optionTalentId == '')) { // 如果有达人店 id 设置并存入缓存
                                    console.log('COVER - 4')
                                    that.setData({
                                        optionTalentId: res.talentId
                                    })
                                    wx.setStorageSync('talentId', res.talentId)
                                }
                                that.initData()
                            }
                        }
                    } else {
                        if (storageTalentId) {
                            console.log('COVER - 1')
                            that.setData({
                                optionTalentId: storageTalentId
                            })
                        }
                        that.initData()
                    }
                },
                fail: res => {
                    if (storageTalentId) {
                        console.log('COVER - 0')
                        that.setData({
                            optionTalentId: storageTalentId
                        })
                    }
                    that.initData()
                }
            })
        }

        this.hotSearch()
    },
    // 获取搜索关键词
    hotSearch() {
        goodsApi.hotSearch().then(res => {
            if (app.globalData.codeConfig.errCode.SUCCESS_CODE === res.data.errCode) {
                this.setData({
                    searchKeyRecommend: res.data.data.keywordList[0]
                })
                app.globalData.searchKeyRecommend = res.data.data.keywordList[0]
            }
        })
    },
    initData() {
        let that = this
        if (!this.data.optionTalentId) {
            // 首页
            that.getIndexData()
        } else {
            // 达人店
            that.getTalentData(false)
        }
    },
    // 获取首页数据
    getIndexData() {
        wx.showNavigationBarLoading()
        wx.setNavigationBarTitle({
            title: '首页'
        })
        let that = this
            // that.$wuxLoading.show({ text: '数据加载中' })
        mallApi.getIndexData({
            startPage: that.data.startPage,
            pageSize: that.data.pageSize
        }).then((res) => {
            wx.hideNavigationBarLoading()
            if (app.globalData.codeConfig.errCode.SUCCESS_CODE === res.data.errCode) {
                let result = res.data.data
                that.setData({
                    bannerList: [...result.bannerList],
                    startPage: result.page.start + '',
                    nextFlag: result.page.nextFlag,
                    goodsList: [...that.data.goodsList, ...result.goodsList],
                    activityList: [...result.activityList],
                    currentPage: 'index'
                })
                that.judgeBottomTextShow(result.page.nextFlag)
            } else {
                that.setData({
                    loadTips: '上拉加载更多',
                    loadNextPageFlag: false
                })
            }
        }).catch((res) => {
            wx.hideNavigationBarLoading()
            that.setData({
                    loadTips: '上拉加载更多',
                    loadNextPageFlag: false
                })
                // that.$wuxLoading.hide()
            console.log(res)
        })
    },
    // 获取达人店数据
    getTalentData(onShowFlag) {
        wx.showNavigationBarLoading()
        wx.setNavigationBarTitle({
            title: '达人店'
        })
        let that = this
        let params = {
            startPage: that.data.startPage,
            pageSize: that.data.pageSize,
            talentId: that.data.optionTalentId
        }
        if (onShowFlag) {
            // onShowFlag 为 true 必定判断过 缓存中有 talentId
            let storageTalentId = wx.getStorageSync('talentId')
            params.talentId = storageTalentId
            params.startPage = '1'
                // 清空缓存中的 talentId ，若 id 合法，在请求返回后会存入缓存
            wx.removeStorageSync('talentId')
        }
        mallApi.getTalentIndexData(params).then((res) => {
            let result = res.data.data
            if (app.globalData.codeConfig.errCode.SUCCESS_CODE === res.data.errCode) {
                wx.hideNavigationBarLoading()
                wx.setStorageSync('talentId', params.talentId)
                let talentInfo = result.talentInfo
                wx.setStorageSync('talentInfo', talentInfo)
                talentInfo.nickName = talentInfo.nickName.length > 10 ? talentInfo.nickName.substr(0, 10) + '...' : talentInfo.nickName
                that.setData({
                    talentId: params.talentId,
                    bannerList: [...result.bannerList],
                    startPage: result.page.start + '',
                    nextFlag: result.page.nextFlag,
                    goodsList: [...that.data.goodsList, ...result.goodsList],
                    activityList: [...result.activityList],
                    talentInfo: {...talentInfo },
                    recommendGoodsList: [...result.recommendGoodsList],
                    currentPage: 'talent'
                })
                if (onShowFlag || result.page.start === 1) {
                    that.setData({
                        goodsList: [...result.goodsList]
                    })
                }
                that.judgeBottomTextShow(result.page.nextFlag)
            } else if (app.globalData.codeConfig.errCode.NO_EXIST_TALENT_ID === res.data.errCode) {
                /**
                 * 场景值解析出的 talentId 是不存在的，
                 * 若此时缓存中有 talentId ，继续调用获取达人店数据的方法
                 * 否则调用获取首页数据的方法
                 */
                let storageTalentId = wx.getStorageSync('talentId')
                if (storageTalentId) {
                    that.getTalentData(true)
                } else {
                    that.getIndexData()
                }
            } else {
                wx.hideNavigationBarLoading()
                that.setData({
                    loadTips: '上拉加载更多',
                    loadNextPageFlag: false
                })
                wx.showToast({ title: res.data.msg, icon: 'none' })
            }
        }).catch((res) => {
            wx.hideNavigationBarLoading()
            that.setData({
                loadTips: '上拉加载更多',
                loadNextPageFlag: false
            })
            wx.showToast({ title: '网络异常，请稍后再试', icon: 'none' })
        })
    },
    // 显示返佣规则
    openCommissionRules() {
        this.setData({
            showCommissionRules: true
        })
    },
    // 控制点击是否显示浮窗
    handleShareChoose() {
        let that = this
        this.setData({
            showChooseSharePop: !that.data.showChooseSharePop
        })
    },
    // 朋友圈分享达人店
    openSharePopup() {
        this.setData({
            showSharePopup: true,
            showChooseSharePop: false
        })
    },
    // 关闭朋友圈达人店分享
    closeSharePopup() {
        this.setData({
            showSharePopup: false
        })
    },
    // 点击搜索框
    onGoSearch() {
        wx.navigateTo({
            url: '../search/search'
        })
    },
    // 点击 banner
    handleBannerTap(e) {
        var isTalent = e.target.dataset.istalent
        let targetUrl = e.target.dataset.url
        let timeStamp = ''
        let that = this
        if (targetUrl === '/pages/vote/vote') {
            wx.showLoading({
                icon: 'none',
                title: ''
            })
            activityApi.getVoteOpenInfo().then((res) => {
                wx.hideLoading()
                if (app.globalData.codeConfig.errCode.SUCCESS_CODE === res.data.errCode) {
                    // 判断 flag 去哪个页面
                    if (res.data.data.openFlag) { // 开启投票了
                        wx.navigateTo({
                            url: `${targetUrl}`
                        })
                    } else { // 木有开启投票
                        timeStamp = res.data.data.voteOpenTime
                        let matchState = res.data.data.matchState
                        wx.navigateTo({
                            url: `/pages/voteCountdown/voteCountdown?timeStamp=${timeStamp}&matchStatus=${matchState}`
                        })
                    }
                } else {
                    // 弹提示
                    wx.showToast({
                        icon: 'none',
                        title: res.data.msg
                    })
                }
            }).catch((res) => {
                // 提示网络错误
                wx.showToast({
                    icon: 'none',
                    title: '网络错误'
                })
            })
        } else {
            wx.hideLoading()
            wx.navigateTo({
                url: `${targetUrl}?isTalent=${isTalent}`
            })
        }
    },
    // 点击金刚区
    onGoSpecialArea(e) {
        let type = e.currentTarget.dataset.item.type
        let name = e.currentTarget.dataset.item.name
        let url = type === 0 ?
            `../specialArea/luckDraw/luckDraw` :
            `../specialArea/specialAreaCommon/specialAreaCommon?name=${name}&type=${type}`
        wx.navigateTo({
            url
        })
    },
    // 点击拔草活动
    onGoActivity(e) {
        let type = e.currentTarget.dataset.item.id
        let name = e.currentTarget.dataset.item.name
        let url = `../activity/activity?name=${name}&type=${type}`
        wx.navigateTo({
            url
        })
    },
    // 阻止冒泡事件，勿删
    handleCatchTap() {},
    // 处理商品点击事件
    handleToGoodsDetail(e) {
        let that = this
        if (that.data.itemTapFlag) return
        that.setData({
            itemTapFlag: false
        })
        wx.navigateTo({
            url: e.currentTarget.dataset.url
        })
    },
    // 隐藏佣金规则
    closeCommissionRules() {
        this.setData({
            showCommissionRules: false,
            firstShared: true
        })
        wx.setStorageSync('firstShared', true)
    },
    // 第一次分享
    handleFirstShare() {
        this.setData({
            showCommissionRules: true
        })
    },
    // 判断底部分割线的文字显示
    judgeBottomTextShow(nextFlag) {
        let that = this
        if (nextFlag) {
            that.setData({
                loadTips: '上拉加载更多',
                loadNextPageFlag: false
            })
        } else {
            that.setData({
                loadTips: '没有更多数据了',
                loadNextPageFlag: false
            })
        }
    },
    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function() {
        let that = this
        let firstShared = wx.getStorageSync('firstShared')
        that.setData({
            itemTapFlag: false,
            firstShared,
            showChooseSharePop: false
        })
        let storageTalentId = wx.getStorageSync('talentId')
        console.log('onshow storageTalentId: ' + storageTalentId)
        if (app.globalData.refreshIndexFlag) {
            if (storageTalentId) {
                that.getTalentData(true)
            } else {
                that.getIndexData()
            }
            app.globalData.refreshIndexFlag = false
        }
    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function() {
        let that = this
        if (that.data.nextFlag) {
            that.setData({
                startPage: (that.data.startPage - 0) + 1 + '',
                loadTips: '加载中...',
                loadNextPageFlag: true
            })
            if (that.data.currentPage === 'index') {
                that.getIndexData()
            } else if (that.data.currentPage === 'talent') {
                that.getTalentData(false)
            }
        }
    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function(e) {
        console.log(e)
        var that = this
        that.setData({
            showChooseSharePop: false
        })
        if (e.from === 'button') {
            let data = e.target.dataset
            if (data.type === 'shop') {
                // 店铺分享
                return {
                    title: '快来我的达人店逛逛吧~',
                    path: that.data.talentId ? '/pages/index/index?talentId=' + that.data.talentId : '/pages/index/index',
                    imageUrl: '/resources/images/index/talent-share-img.png'
                }
            } else if (data.type === 'goods') {
                // 商品分享
                return {
                    title: data.name,
                    path: data.url,
                    imageUrl: data.img
                }
            }
        } else if (e.from === 'menu') {
            // 小程序分享
            return {
                title: '发现一个好东西，快来围观！',
                path: '/pages/index/index'
                    // imageUrl: 
            }
        }
    }
})